import {login, logout, getInfo} from '@/api/login'
import {getToken, setToken, removeToken, setRoles, removeRoles} from '@/utils/auth'

const user = {
  state: {
    token: getToken(),
    name: '',
    orgName: '',
    roles: ['A:B:*', 'C:A:B'],
    avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
    info: null,
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_ORG_NAME: (state, orgName) => {
      state.orgName = orgName
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_USER_INFO: (state, userInfo) => {
      state.userInfo = userInfo
    },
  },

  actions: {
    // 登录
    Login({commit}, userInfo) {
      const loginName = userInfo.loginName.trim()
      const password = userInfo.password
      const code = userInfo.code
      const uuid = userInfo.uuid
      return new Promise((resolve, reject) => {

        login(loginName, password, code, uuid).then(res => {
          let {data: {token}} = res
          setToken(token)
          commit('SET_TOKEN', token)

          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({commit, state}) {
      return new Promise((resolve, reject) => {
        getInfo().then(res => {
          const user = res.data
          user.avatar = user.avatar != null && user.avatar != '' ? `/fileDown/${user.avatar}` : 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
          let {nickName, orgName, permissionExpressions, avatar} = user;
          removeRoles()
          setRoles(permissionExpressions)

          commit('SET_USER_INFO', _.cloneDeep(user))
          commit('SET_NAME', nickName)
          commit('SET_ORG_NAME', orgName)
          commit('SET_AVATAR', avatar)
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 退出系统
    LogOut({commit, state}) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          removeToken()
          removeRoles()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    FedLogOut({commit}) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        removeRoles()
      })
    }
  }
}

export default user
